package assist.datastore.parser;

import java.io.IOException;
import java.io.Reader;

import assist.datastore.parser.exception.PlayerNotFoundException;
import assist.domain.model.Event;
import assist.domain.model.Game;
import assist.domain.model.Player;

import com.google.gson.Gson; 
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

public class NHLPlayByPlayJSONParser
{
    private Game game;
    private JsonReader jsonReader;
    
    public NHLPlayByPlayJSONParser(final Game game, final Reader reader)
        throws IOException
    {
        this.game = game;
        this.jsonReader = new JsonReader(reader);      
        this.parse();
        this.jsonReader.close();
    }

    public void parse() throws IOException
    {
        JsonParser parser = new JsonParser();
        JsonObject jsonData = (JsonObject) ((JsonObject)parser.parse(jsonReader)).get("data");       
        JsonElement jsonGameElement = jsonData.get("game");
        Gson gson = new Gson();               
        JsonNhlGame jsonGame = gson.fromJson(jsonGameElement, JsonNhlGame.class);
        this.addStatsFromJson(jsonGame);

        
    }

    private void addStatsFromJson(JsonNhlGame jsonGame)
    {
        for(JsonNhlGame.Play play : jsonGame.plays.play)
        {
            System.err.println("Adding Play: " + play.desc);
            final Event event = 
                NHLEventFactory.createEvent(play.type,
                        play.period, play.time);
            this.addEventToGame(event, play);
            
        }
    }
    
    private void addEventToGame(Event event, JsonNhlGame.Play play)
    {
        System.err.println("TODO");
        //game.addEvent(event, NHLTeamFactory.createFromId(play.teamid));
    }
    
    private static Player getPlayerFromGame(final Game game, 
            final Integer number, final String team)
    {
        if (number == null || team == null)
        {
            throw new IllegalArgumentException("Team and " +
                    "Player number must be set for this Event type.");
        }
        final Player player = game.getGameStats(NHLTeamFactory.createFromAbbreviation(team)).getRoster().getPlayer(number);
        if (player == null)
        {
            throw new PlayerNotFoundException(team, number);
        }
        return player;
    }    

    public Game getGame()
    {
        // TODO Auto-generated method stub
        return this.game;
    }
}

class JsonNhlGame
{
    String awayteamname;
    String hometeamname;
    Plays plays;    
    static class Plays
    {
        Play [] play;
    }
    static class Play
    {
        String desc;
        Integer period;
        String type;
        String time;
        Integer teamid;
        String p1name;
        String p2name;
    }    
}
